﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Security.AccessControl;


namespace WpfWordsLearner
{
	[RunInstaller(true)]
	public partial class InstallerModule : System.Configuration.Install.Installer
	{
		public InstallerModule()
		{
			InitializeComponent();
		}

		protected override void OnAfterInstall(IDictionary savedState)
		{
			base.OnAfterInstall(savedState);

			if (!Context.Parameters.ContainsKey("TD"))
				return;

			bool isFound = false;
			string path = Context.Parameters["TD"].Substring(0, Context.Parameters["TD"].Length - 1);
			if (System.IO.Directory.Exists(path))
			{
				foreach (string folder in System.IO.Directory.EnumerateDirectories(path))
				{
					if (string.Compare(System.IO.Path.GetDirectoryName(folder), "Log", true) == 0)
						isFound = true;
					
					try
					{
						SetSecurity(path);
						SetDirAccess(path);
					}
					catch (System.IO.IOException ex) { Context.LogMessage(ex.Message); }
					catch (System.UnauthorizedAccessException ex) { Context.LogMessage(ex.Message); }
					catch (System.ArgumentException ex) { Context.LogMessage(ex.Message); }
				}
			}

			if (!isFound && !System.IO.Directory.Exists(System.IO.Path.Combine(path, "Log")))
			{
				try
				{
					System.IO.Directory.CreateDirectory(System.IO.Path.Combine(path, "Log"));
				}
				catch (System.IO.IOException ex) { Context.LogMessage(ex.Message); }
				catch (System.UnauthorizedAccessException ex) { Context.LogMessage(ex.Message); }
			}
		}

		private void SetSecurity(string folderPath)
		{
			var diInfo = new System.IO.DirectoryInfo(folderPath);
			var diSec = diInfo.GetAccessControl();
			System.Security.Principal.SecurityIdentifier identifier = new System.Security.Principal.SecurityIdentifier(
																			System.Security.Principal.WellKnownSidType.WorldSid, null);
			var accessRule = new System.Security.AccessControl.FileSystemAccessRule(identifier,
								FileSystemRights.FullControl,
								InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
								PropagationFlags.None, AccessControlType.Allow);
			diSec.AddAccessRule(accessRule);
		}

		private void SetDirAccess(string path)
		{
			DirectorySecurity sec = System.IO.Directory.GetAccessControl(path);
			// Using this instead of the "Everyone" string means we work on non-English systems.
			var everyone = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
			sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl,
				InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
			System.IO.Directory.SetAccessControl(path, sec);
		}
	}
}
